import java.util.ArrayList;
import java.util.List;

/**
 * 普通轮询算法
 */
public class RoundRobin {
    private static Integer index = 0;
    private static final List<String> nodes = new ArrayList<>();    // 准备模拟数据

    static {
        nodes.add("192.168.1.101");
        nodes.add("192.168.1.103");
        nodes.add("192.168.1.102");
        System.out.println("普通轮询算法的所有节点：" + nodes);//打印所有节点
    }        // 关键代码

    public String selectNode() {
        String ip = null;
        synchronized (index) {
            // 下标复位
            if (index >= nodes.size()) index = 0;
            ip = nodes.get(index);
            index++;
        }
        return ip;
    }

    // 并发测试：两个线程循环获取节点
    public static void main(String[] args) {
        new Thread(() -> {
            RoundRobin roundRobin1 = new RoundRobin();
            for (int i = 1; i <= 5; i++) {
                String serverIp = roundRobin1.selectNode();
                System.out.println(Thread.currentThread().getName() + "==第" + i + "次获取节点：" + serverIp);
            }
        }).start();
        RoundRobin roundRobin2 = new RoundRobin();
        for (int i = 1; i <= nodes.size(); i++) {
            String serverIp = roundRobin2.selectNode();
            System.out.println(Thread.currentThread().getName() + "==第" + i + "次获取节点：" + serverIp);
        }
    }
}